import { Component, ViewChild } from '@angular/core';
import { Events, Nav, NavController, Platform, App, ModalController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { Keyboard } from '@ionic-native/keyboard';
import { BackgroundMode } from '@ionic-native/background-mode';
import { Storage } from '@ionic/storage';
import { TabsPage } from '../pages/tabs/tabs.component';
import { LoginPage } from '../pages/login/login.component';
import { LockPage } from '../pages/lock/lock.component';
import { TutorialPage } from '../pages/tutorial/tutorial.component';
import { LocalNotifications } from '@ionic-native/local-notifications';

import { Config } from '../providers/config';

import { Common } from '../providers/common';


import _ from 'lodash';


@Component({
  templateUrl: 'app.template.html'
})
export class GfoaApp {
  // the root nav is a child of the root app component
  // @ViewChild(Nav) gets a reference to the app's root nav
  @ViewChild(Nav) nav: Nav;

  rootPage: any;

  constructor(
    public events: Events,
    public platform: Platform,
    public storage: Storage,
    public modalCtrl: ModalController,
    public app: App,
    public keyboard: Keyboard,
    public statusBar: StatusBar,
    public backgroundMode: BackgroundMode,
    public common: Common,
    public config: Config,
    public localNotifications: LocalNotifications
  ) {
    let that = this;
    this.checkTutorial();

    that.localNotifications.on("click", (notification, state) => {
      that.events.publish("NotifyToGoPage", notification);
    });

    this.app.viewDidLoad.subscribe(view => {
      // console.log("this.app>>viewDidLoad>>>>>>>>> >>", this.app);
      // console.log("----------viewDidLoad.view----------", view);

      /*this.storage.get("UserStatistics").then(UserStatistics => {
        console.log("UserStatistics>>>>", UserStatistics);
      })*/
    });
    this.app.viewWillLeave.subscribe((view) => {
      // 为了解决页面离开，水印延迟消失的问题
      var current_pages = document.getElementsByTagName(view.instance.moa_page_name);
      for (var index = 0; index < current_pages.length; index++) {
        if (_.indexOf(current_pages[index].classList, 'show-page') > -1) {
          var watermarkDivs = current_pages[index].getElementsByClassName("watermark_mask_div");
          _.each(watermarkDivs, function (item: any, index) {
            item.style.display = "none";
          });
        }
      }
    });

    // 页面进来时，检测是否需要添加水印
    this.app.viewWillEnter.subscribe((view) => {
      this.common.addWatermark(view);
    });

    this.app.viewDidEnter.subscribe(view => {
      if (view) {
        this.common.saveUserStatistics(view.instance.moa_page_name, "", view.instance.moa_page_explain);
      }
    })
  }

  // 检查是否已经查看过引导页面
  checkTutorial() {
    this.checkLogin();
    // 先隐藏引导页，后续大版本更新，再开启回来
    // this.storage.get('hasSeenTutorial-' + this.config.tutorialVersion).then(isSeenTutorial => {
    //   if (isSeenTutorial) {
    //     this.checkLogin();
    //   } else {
    //     this.rootPage = TutorialPage;
    //     this.platformReady();
    //   }
    // });
  }

  // 检查是否登录
  checkLogin() {
    if (this.config.isProduct) {
      console.info('------checkLogin isProduct true----------');
      // window.location.hash = '/';
      this.rootPage = LoginPage;
      this.platformReady();
    } else {
      this.storage.get('id_token').then(token => {
        if (!token) {
          this.rootPage = LoginPage;
        } else {
          if (!window.location.hash) {
            this.rootPage = TabsPage;
          }
        }
        this.platformReady();
      });
    }
  };

  showLockPage() {
    let that = this;
    this.storage.get('lockPassword').then((lockPassword) => {
      if (lockPassword) {
        that.storage.get("isLock").then((isLock) => {
          // 如果是在锁屏状态，禁用返回键
          if (!isLock) {
            let modal = this.modalCtrl.create(LockPage, {});
            modal.present();
            modal.onWillDismiss((data: any[]) => {
              console.info(data);
            });
          }
        });

      }
    });
  }
  // openTutorial() {
  //   this.nav.setRoot(TutorialPage);
  // }
  platformReady() {
    let that = this;

    // setInterval(function() {
    //   console.info('---------------------------');
    //   console.info(that.nav);
    //   console.info(that.app);
    // }, 3000);
    // Call any initial plugins when ready
    this.platform.ready().then(() => {


      // 键盘显示完成按钮
      this.keyboard.hideKeyboardAccessoryBar(false);

      if (this.config.isProduct) {
        // 检查更新应用
        this.common.checkUpdate({
          isShowLoading: false,
          isAlterTips: false
        });
      }

      // 开启背景进程
      this.backgroundMode.enable();
      // 延后隐藏启动画面
      setTimeout(function (argument) {
        if (navigator['splashscreen']) {
          navigator['splashscreen'].hide();
        }
      }, 1000);

      if (window['cordova'] && this.platform.is('android')) {
        this.backgroundMode.setDefaults({
          "title": "广发办公",
          "text": "移动办公门户",
          "silent": true
        });
      }

      // 初始化推送通知
      if (window['PushNotification'] && this.platform.is('ios')) {
        window['push'] = window['PushNotification'].init({
          ios: {
            alert: true,
            badge: true,
            clearBadge: true,
            sound: true
          }
        });
        // 获取推送token
        window['push'].on('registration', function (data) {
          console.log('------------registration------------');
          console.log(data.registrationId);
          that.storage.set('registrationId', data.registrationId);
        });
        // 处理接收到的推送信息
        window['push'].on('notification', function (data) {
          console.log(data.message);
          console.log(data.title);
          console.log(data.count);
          console.log(data.sound);
          console.log(data.image);
          console.log(data.additionalData);
        });
      }

      window.addEventListener('native.keyboardhide', function () {
        console.log('----------native.keyboardhide------------')
        if (that.platform.is('android') && that.app['_title'] == '通讯录') {
          console.info('-----触发刷新通讯录操作------');
          that.events.publish("refresh-contact-list-on-keyboard-hide", {});
        }
      });

      window.addEventListener('native.keyboardshow', function () {
        console.log('----------native.keyboardshow------------')
        if (that.app['_title'] == '通讯录') {
          console.info('-----触发隐藏通讯录选中条------');
          that.events.publish("hide-contact-tips-on-keyboard-show", {});
        }
      });


      this.platform.registerBackButtonAction(() => {
        that.storage.get("isLock").then((isLock) => {
          // 如果是在锁屏状态，禁用返回键
          if (!isLock) {
            let isGoBackgroundMode = false;
            var title = that.app['_title'];
            var mainTitles = ['首页', '工作台', '通讯录', '设置', '登录'];
            // 判断标题是否和这个几个页面相同
            console.info('-----------current page title----------');
            console.info(title);
            _.each(mainTitles, function (item, index) {
              if (title.indexOf(item) > -1 && title != "营销首页" && title != "风控首页") {
                isGoBackgroundMode = true;
              }
            });
            if (isGoBackgroundMode) {
              console.info('----------moveToBackground ----------');
              window['cordova'].plugins.backgroundMode.moveToBackground();
            } else {
              // 如果有值，则关闭所有loading
              if (window['gfoa_loading']) {
                window['gfoa_loading'].dismissAll();
              }
              that.app.goBack();
            }

            // var currentPageName = _.last(that.nav._linker.segments).name;
            // console.info('--------------currentPageName---------------');
            // console.info(currentPageName);
            // // 如果是以下几个地址，则直接退出到后台
            // if (_.indexOf(['MainPage', 'WorkIndexPage', 'ContactListPage', 'SettingIndexPage', 'LoginPage'], currentPageName) > -1) {
            //   console.info('----------moveToBackground ----------');
            //   window['cordova'].plugins.backgroundMode.moveToBackground();
            // } else {
            //   that.app.goBack();
            // }
          }
        });
      }, 0);

      document.addEventListener("pause", function () {
        // 如果记录当前退出的时间
        that.storage.set('pause_time', (new Date()).getTime());
      }, false);

      document.addEventListener("resume", function () {
        console.info('come back');
        // 读取上次退出时间，如果超过一定时间，则弹出手势密码
        that.storage.get('pause_time').then((pause_time) => {
          let now = (new Date()).getTime();
          // 如果5秒后回来。就弹出
          if (now - pause_time > that.config.lockTime) {
            that.showLockPage();
          }
        });
      }, false);


      if (this.platform.is('android')) {
        this.statusBar.backgroundColorByHexString('#fc7a00');
      }

    });
  }
}
